﻿Imports System.Data.SqlClient
Imports System.IO
Imports System.Xml
Imports System.Data
Imports Microsoft.Win32
Imports Microsoft.ReportingServices
Imports Microsoft.Reporting.WinForms




Public Class FrmPresupuesto
    'Private oPedido As New txtpedido

    Private carrito As New DataTable("Detalle")
    Private dr As DataRow
    Private stock As Integer
    Private total As Single
    Private fila As Byte
    Dim idcliente As String
    Protected Const conexion As String = "Data Source=localhost;Initial Catalog=RCBD;Integrated Security=True"
    Dim formatotext As clsFormulario
    Public correlativoc As Integer
    Dim totalpres As Integer



    Private Sub FrmPedidosN_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        llenarcbocli()
        llenarcbocont()
        llenarcboprod()
        ConfiguraTabla()
        'cn.Dispose()
        limpiar()
        inhabilitar()
    End Sub
    Private Sub habilitar()
        '****Inhabilitar los textbox
        'txtnroorden.Enabled = True
        txtcantidad.Enabled = True
        txtobs.Enabled = True
        dtpfecha.Enabled = True
        dtpfechavenc.Enabled = True
        dgvdetalle.Enabled = True
        '****Inhabilitar los combobox
        cmbcliente.Enabled = True
        cmbcontactos.Enabled = True
        cmbproducto.Enabled = True
        '****inhabilitar los botones
        btnagregar.Enabled = True
        btneliminar.Enabled = True
        btnguardar.Enabled = True
        btnbuscarcli.Enabled = True
        btnagregarcli.Enabled = True
        btncancelar.Enabled = True
        '****Inhabilitar los botones para agregar una nueva nota
        btnnuevo.Enabled = False
        btncerrar.Enabled = False

    End Sub
    Private Sub inhabilitar()
        '****Inhabilitar los textbox
        txtcodcli.Enabled = False
        txtdireccion.Enabled = False
        txtnumero.Enabled = False
        txtprecio.Enabled = False
        'txtstock.Enabled = False
        txttelefono.Enabled = False
        txttotal.Enabled = False
        'txtnroorden.Enabled = False
        txtcantidad.Enabled = False
        txtobs.Enabled = False
        dtpfecha.Enabled = False
        dtpfechavenc.Enabled = False
        dgvdetalle.Enabled = False
        '****Inhabilitar los combobox
        cmbcliente.Enabled = False
        cmbcontactos.Enabled = False
        cmbproducto.Enabled = False
        '****cambiar el color del fondo a los textbox
        txtcodcli.BackColor = System.Drawing.Color.White
        txtdireccion.BackColor = System.Drawing.Color.White
        txtnumero.BackColor = System.Drawing.Color.White
        txtprecio.BackColor = System.Drawing.Color.White
        'txtstock.BackColor = System.Drawing.Color.White
        txttelefono.BackColor = System.Drawing.Color.White
        txttotal.BackColor = System.Drawing.Color.White
        'txtnroorden.BackColor = System.Drawing.Color.White
        txtcantidad.BackColor = System.Drawing.Color.White
        cmbcliente.BackColor = System.Drawing.Color.White
        cmbcontactos.BackColor = System.Drawing.Color.White
        cmbproducto.BackColor = System.Drawing.Color.White
        '****inhabilitar los botones
        btnagregar.Enabled = False
        btneliminar.Enabled = False
        btnguardar.Enabled = False
        btnbuscarcli.Enabled = False
        btnagregarcli.Enabled = False
        btncancelar.Enabled = False
        '****habilitar los botones para crear una nueva nota
        btnnuevo.Enabled = True
        btncerrar.Enabled = True
    End Sub

    Private Sub limpiar()
        cmbcliente.Text = ""
        cmbproducto.Text = ""
        cmbcontactos.Text = ""
        cmbproducto.Text = ""
        txtcodcli.Text = ""
        txtdireccion.Text = ""
        txttelefono.Text = ""
        txtprecio.Text = ""
        'txtstock.Text = ""
        txtcantidad.Text = ""
        txttotal.Text = ""
        'txtnroorden.Text = ""
        txtnumero.Text = ""
        txtobs.Text = ""

    End Sub
    Private Sub llenarcbocli()
        Dim ob As New Clientes
        'Dim tx As String
        Dim origen As String = "SELECT codcliente, nombre, direccion, telefono FROM dbo.Clientes"
        Dim dsclientes As DataTable
        dsclientes = Sql.Llenar(conexion, origen, )
        With Me.cmbcliente
            .DisplayMember = "nombre"
            .ValueMember = "codcliente"
            .DataSource = dsclientes
            '.SelectedIndex = -1
        End With

    End Sub
    Private Sub llenarcbocont()
        Dim ob As New Contactos
        'Dim tx As String
        Dim origen As String = "SELECT codcontacto, nombre FROM dbo.CONTACTOS"
        Dim dscontacto As DataTable
        dscontacto = Sql.Llenar(conexion, origen, )
        With Me.cmbcontactos
            .DisplayMember = "nombre"
            .ValueMember = "codcontacto"
            .DataSource = dscontacto
            .SelectedIndex = -1
        End With

    End Sub

    Private Sub cmbcliente_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbcliente.SelectedIndexChanged
        ArmaClientes()
    End Sub
    Private Sub ArmaClientes()
        Dim ob As New Clientes
        Dim tx As String

        tx = Sql.Cargar(conexion, "dbo.CLIENTES", "codcliente= " & cmbcliente.SelectedValue, ob, "")

        If tx = "" Then
            txtcodcli.Text = ob.codcliente
            txtdireccion.Text = ob.nombre
            txttelefono.Text = ob.telefono
            txtdireccion.Text = ob.direccion

        Else
            MessageBox.Show(tx)
        End If
    End Sub
    Private Sub llenarcboprod()
        Dim ob As New Productos
        'Dim tx As String
        Dim origen As String = "SELECT codproducto, descripcion, precioventa, cantexistente FROM dbo.PRODUCTOS"
        Dim dsproducto As DataTable
        dsproducto = Sql.Llenar(conexion, origen, )
        With Me.cmbproducto
            .DisplayMember = "descripcion"
            .ValueMember = "codproducto"
            .DataSource = dsproducto
            '.SelectedIndex = -1
        End With

    End Sub
    Private Sub ArmaProducto()
        Dim ob As New Productos
        Dim tx As String

        tx = Sql.Cargar(conexion, "dbo.PRODUCTOS", "codproducto= " & cmbproducto.SelectedValue, ob, "")

        If tx = "" Then

            txtprecio.Text = FormatNumber(ob.precioventa, 0, , , TriState.True)
            'txtstock.Text = ob.cantexistente
        Else
            MessageBox.Show(tx)
        End If
    End Sub
    Private Sub ConfiguraTabla()
        Dim dc0 As New DataColumn("Item", System.Type.GetType("System.Byte"))
        Dim dc1 As New DataColumn("Codigo", System.Type.GetType("System.Int16"))
        Dim dc2 As New DataColumn("Descripcion", System.Type.GetType("System.String"))
        Dim dc3 As New DataColumn("Cantidad", System.Type.GetType("System.Int16"))
        Dim dc4 As New DataColumn("Precio", System.Type.GetType("System.Decimal"))
        Dim dc5 As New DataColumn("Total", System.Type.GetType("System.Decimal"))

        dc1.Unique = True
        dc5.Expression = "Cantidad*Precio"
        With carrito.Columns
            .Add(dc0)
            .Add(dc1)
            .Add(dc2)
            .Add(dc3)
            .Add(dc4)
            .Add(dc5)
        End With
        dgvdetalle.DataSource = carrito

    End Sub


    Private Sub cmbproducto_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbproducto.SelectedIndexChanged
        ArmaProducto()
    End Sub



    Private Sub btnagregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnagregar.Click
        Try
            If Me.txtcantidad.Text = "" Then
                MessageBox.Show("Falta llenar datos del detalle", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                Me.txtcantidad.Focus()
            Else
                dr = carrito.NewRow()
                dr(0) = carrito.Rows.Count + 1
                dr(1) = cmbproducto.SelectedValue.ToString
                dr(2) = cmbproducto.Text
                dr(3) = txtcantidad.Text
                dr(4) = txtprecio.Text
                dr(5) = txttotal.Text
                carrito.Rows.Add(dr)
                'totales()
                Me.txtcantidad.Text = ""
                Me.cmbproducto.Text = ""
                Me.txtprecio.Text = ""
                Me.txttotal.Text = ""
                'Me.txtstock.Text = ""
            End If

        Catch ex1 As System.Data.ConstraintException
            MsgBox("El producto ya ha sido seleccionado", MsgBoxStyle.Critical, "Verificar")
            txtcantidad.Text = ""
            cmbproducto.Focus()

        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            cn.Close()
        End Try



    End Sub



    Private Sub txttotal_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txttotal.GotFocus

    End Sub

    Private Sub txtcantidad_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtcantidad.KeyUp
        'pasamos  los parametros al sub KeyUp que creamos
        Me.KeyUp(Me.txtcantidad, e)
    End Sub

    Private Sub txtcantidad_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.TextChanged

        'Try
        Dim a, c, d As Integer
        a = Val(txtcantidad.Text)
        'b = Val(Me.txtstock.Text)
        c = (Me.txtprecio.Text)

        'If a <= b Then
        d = a * c
        txttotal.Text = FormatNumber(d, 0, , , TriState.True)
        totalpres = totalpres + CInt(txttotal.Text)

        '    Else
        '    MsgBox("No hay Stock suficiente", MsgBoxStyle.Exclamation, "Stock del Producto")
        '    txtcantidad.Text = "1"
        '    d = 1 * c
        '    txttotal.Text = d
        '    End If

        'Catch ex As Exception
        '    MsgBox(ex.Message)
        'End Try
    End Sub

    Private Sub btnguardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnguardar.Click

        If carrito.Rows.Count >= 1 Then
            If txtcodcli.Text <> "" Then
                Dim addpresupuesto As SqlCommand
                Dim valfecha As Date
                Dim valfechavenc As Date
                valfecha = CDate(dtpfecha.Value).ToString("yyyy/MM/dd")
                valfechavenc = CDate(dtpfechavenc.Value).ToString("yyyy/MM/dd")
                addpresupuesto = New SqlCommand("dbo.presupuestoAdd", cn)
                addpresupuesto.CommandType = CommandType.StoredProcedure
                addpresupuesto.Parameters.AddWithValue("@nronota", SqlDbType.Int).Value = CInt(txtnumero.Text)
                addpresupuesto.Parameters.AddWithValue("@codcliente", SqlDbType.Int).Value = CInt(txtcodcli.Text)
                addpresupuesto.Parameters.AddWithValue("@fecha", SqlDbType.Date).Value = valfecha
                addpresupuesto.Parameters.AddWithValue("@codestadonota", SqlDbType.Int).Value = 1
                addpresupuesto.Parameters.AddWithValue("@codcontacto", SqlDbType.Int).Value = CInt(cmbcontactos.SelectedValue)
                addpresupuesto.Parameters.AddWithValue("@total", SqlDbType.Money).Value = totalpres
                addpresupuesto.Parameters.AddWithValue("@codtiponota", SqlDbType.Int).Value = 2
                addpresupuesto.Parameters.AddWithValue("@fechavencimiento", SqlDbType.Date).Value = valfechavenc
                addpresupuesto.Parameters.AddWithValue("@observacion", SqlDbType.Text).Value = CStr(txtobs.Text)
                Try
                    cn.Open()
                    addpresupuesto.ExecuteNonQuery()
                Catch ex As Exception
                    MessageBox.Show(ex.Message)

                Finally
                    cn.Close()
                End Try
                Dim cmd2 As New SqlCommand("select max(codnota) from dbo.NOTAS WHERE codtiponota=2", cn)
                cn.Open()
                correlativoc = cmd2.ExecuteScalar()
                Dim i As Integer
                For i = 0 To carrito.Rows.Count - 1
                    Dim cmd3 As New SqlCommand("insert into dbo.DETALLENOTAS (codnota, codproducto, cantidad, precio)values('" & correlativoc & "','" & carrito.Rows(i)(1) & "','" & carrito.Rows(i)(3) & "','" & carrito.Rows(i)(4) & "' )", cn)
                    cmd3.ExecuteNonQuery()
                Next
                MsgBox("Su transaccion ha sido aceptada Generándose el número de pedido : " & txtnumero.Text)
                'btnnuevo.Visible = True
                carrito.Rows.Clear()
                Try
                Catch ex As Exception
                    MsgBox(ex.Message)
                Finally
                    cn.Close()
                End Try
                FrmImpPed.Show()
                inhabilitar()
                limpiar()
            Else
                MessageBox.Show("Debe seleccionar el Cliente", "Datos Incompletos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

            End If
        Else
            MessageBox.Show("No ha seleccionado ningún Producto", "Datos Incompletos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub


    Private Sub dtpfecha_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpfecha.ValueChanged

    End Sub

    Private Sub btncerrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncerrar.Click
        Me.Close()
    End Sub




    Private Sub dtpfechavenc_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpfechavenc.ValueChanged
        Dim f1 As Date
        Dim f2 As Date
        f1 = FormatDateTime(dtpfechavenc.Value, DateFormat.ShortDate)
        f2 = FormatDateTime(dtpfecha.Value, DateFormat.ShortDate)
        If f1 >= f2 Then


        Else
            MsgBox("La Fecha de Vencimiento no Puede ser menor a la fecha del Pedido")
            dtpfechavenc.Value = Today
        End If

    End Sub


    'Permite que el Textbox solo acepte Numeros

    'Nombre del TextBox que quiere validar para que acepte numeros </param>
    'Pase la letra 'e' como valor en el evento KeyUp</param>

    Private Shadows Sub KeyUp(ByVal TextBoxs As System.Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 _
            Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And TextBoxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            TextBoxs.Text.Remove(TextBoxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf TextBoxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            TextBoxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            TextBoxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub




    'Private Sub txtnroorden_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtnroorden.KeyUp
    '    'pasamos  los parametros al sub KeyUp que creamos
    '    Me.KeyUp(Me.txtnroorden, e)

    'End Sub




    Private Sub btneliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btneliminar.Click
        Try
            fila = dgvdetalle.CurrentCell.RowIndex
            If fila > -1 And carrito.Rows.Count > 0 Then
                totalpres -= Integer.Parse(dgvdetalle.Item(4, fila).Value)
                carrito.Rows.RemoveAt(fila)
                Dim i As Integer
                For i = 0 To carrito.Rows.Count - 1
                    carrito.Rows(i).BeginEdit()
                    carrito.Rows(i)(0) = i + 1
                    carrito.Rows(i).EndEdit()
                Next
                ' totales()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            cn.Close()
        End Try
    End Sub

    Private Sub btnnuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnnuevo.Click
        Dim correlativo As Integer
        Dim cmd2 As New SqlCommand("select max(nronota) from dbo.NOTAS WHERE codtiponota= 2", cn)
        cn.Open()
        correlativo = CInt(cmd2.ExecuteScalar()) + 1
        txtnumero.Text = correlativo
        cn.Close()
        habilitar()
        totalpres = 0
    End Sub




    Private Sub dgvdetalle_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellContentClick

    End Sub

    Private Sub txtstock_TextChanged(sender As System.Object, e As System.EventArgs)

    End Sub

    Private Sub gbrdetalle_Enter(sender As System.Object, e As System.EventArgs) Handles gbrdetalle.Enter

    End Sub

    Private Sub btncancelar_Click(sender As System.Object, e As System.EventArgs) Handles btncancelar.Click
        limpiar()
        inhabilitar()
        carrito.Rows.Clear()
    End Sub
End Class